package cn.huanglei936.essay.thymeleaf.controller;

import cn.huanglei936.essay.thymeleaf.ro.ReqImgToPdf;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 *
 * @author huanglei
 * @email lhuang@matmass.com
 * @data 2018/10/29 15:04
 */
@RestController
@RequestMapping("/imgToPdf")
public class ImgToPdf {

    @Value("${standard.img.rootpath}")
    private String imgRootPath;
    @Value("${standard.pdf.rootpath}")
    private String pdfRootPath;

    @RequestMapping("execute")
    public Map<String, Integer> execute(@RequestBody ReqImgToPdf reqImgToPdf) throws IOException, DocumentException {

        List<String> imgs = reqImgToPdf.getImgs();
        Map<String, Integer> map = new HashMap<>();
        if (Objects.nonNull(imgs) && imgs.size() > 0) {
            String pdfName = reqImgToPdf.getName();
            int indexOfPdf = pdfName.indexOf("pdf");
            if (indexOfPdf == -1) {
                pdfName = pdfName + ".pdf";
            }
            pdfName = pdfName.replace("GB/", "GB ");
            pdfName = pdfName.replace("\\", "-");
            pdfName = pdfName.replace("/", "-");
            pdfName = pdfName.replace(":", "：");
            String pdfPath = pdfRootPath + File.separator + pdfName;
            List<String> fullImgs = new ArrayList<>();
            for (String img : imgs) {
                img = imgRootPath + File.separator + img;
                fullImgs.add(img);
            }
            Image img = Image.getInstance(fullImgs.get(0));
            Document document = new Document(img);
            FileOutputStream fileOutputStream = new FileOutputStream(pdfPath);
            PdfWriter.getInstance(document, fileOutputStream);
            document.open();
            for (String image : fullImgs) {
                img = Image.getInstance(image);
                document.setPageSize(img);
                document.newPage();
                img.setAbsolutePosition(0, 0);
                document.add(img);
            }
            document.close();

        }
        return map;
    }

    public static void main(String[] args) {
        String s = "车辆 电气\\电子部件对窄带";
        System.out.println(s);
        s = s.replace("\\", "-");
        System.out.println(s);
    }
}
